package org.hgvc.webapp.ets.jsf.beans.mastersetup;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.faces.component.UIParameter;
import javax.faces.event.ActionEvent;

import org.hgvc.webapp.ets.bo.Agent;
import org.hgvc.webapp.ets.constant.CommonConstant;
import org.hgvc.webapp.ets.spring.service.MasterSetupService;
import org.jocsb.base.AbstractBean;
import org.jocsb.base.exception.BaseException;


public class AgentBean extends AbstractBean {
	public static final String BEAN_NAME="agentBean";
	private MasterSetupService service;
	private List<Agent> agentList;
	private Agent agent;
	public static final String NAV_LIST_AGENT="listAgent";
	public static final String NAV_ADD_AGENT="addAgent";
	public static final String NAV_EDIT_AGENT="editAgent";
	 
	public MasterSetupService getService() {
		return service;
	}
	public void setService(MasterSetupService service) {
		this.service = service;
	}
	public Agent getAgent() {
		return agent;
	}
	public void setAgent(Agent agent) {
		this.agent = agent;
	}
	public List<Agent> getAgentList() {
		try{
			agentList = service.getAgentList();
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		return agentList;
	}
	public void setAgentList(List<Agent> agentList) {
		this.agentList = agentList;
	}
	
	public String navCreationAction(){
		agent = new Agent();
		return NAV_ADD_AGENT;
	}
	
	public String createAction(){
		try{
			agent.setCreatedBy(getThisUser());
			agent.setCreatedDate(new Date());
			agent.setIsDeleted(CommonConstant.NOT_DELETED);
			service.saveAgent(agent);
			return NAV_LIST_AGENT;
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		return NAV_ADD_AGENT;
	}
	
	public void editListener(ActionEvent actionEvent){
		agent = null;
		UIParameter parameter = (UIParameter)actionEvent.getComponent().findComponent("agentId");
		String agentId = (String)parameter.getValue();
		for(Agent a:agentList){
			if(a.getAgentId().equalsIgnoreCase(agentId)){
				agent = a;
				break;
			}
		}
	}
	
	public String navEditAction(){
		return NAV_EDIT_AGENT;
	}
	
	public String editAction(){
		try{
			agent.setModifiedBy(getThisUser());
			agent.setModifiedDate(new Date());
			service.updateAgent(agent);
			return NAV_LIST_AGENT;
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		
		return NAV_EDIT_AGENT;
	}
	
	public String deleteAction(){
		try{
			
			List<Agent> deleteList = new ArrayList<Agent>();
			for(Agent a:agentList){
				if(a.isMarkAsAction()){
					deleteList.add(a);
				}
			}
			service.deleteAgents(deleteList);
		}catch(BaseException ex){
			ex.printStackTrace();
			initErrorBean(ex);
		}
		return NAV_LIST_AGENT;
	}
	
	  //testing
    public String testing(String... params){
    	
    	return NAV_LIST_AGENT;
    }
}
